import {
  Card,
  Breadcrumb,
  Form,
  Button,
  Radio,
  Input,
  Upload,
  Space,
  Select,
  message,
} from "antd";
import { PlusOutlined } from "@ant-design/icons";
import { Link, useSearchParams } from "react-router-dom";
import "./index.scss";
import Vditor from "vditor";
import "vditor/dist/index.css";
import { useEffect, useState } from "react";
import { apiSubmitArticle, apiArticleDetail } from "@/apis/publish";
import useChannels from "@/hooks/useChannels";
const { Option } = Select;

const Publish = () => {
  const [forminstace] = Form.useForm();
  // 编辑功能
  //1. 路由id
  const [params] = useSearchParams();
  const [hasId, setHasId] = useState("");
  const [messageApi, contextHolder] = message.useMessage();
  const channels = useChannels();
  // Vditor的使用教程
  const [vd, setVd] = useState();
  useEffect(() => {
    const vditor = new Vditor("vditor", {
      height: "500px",

      after: () => {
        vditor.setValue("初始化");
        setVd(vditor);
      },
    });
    setHasId(params.get("id"));

    async function getArticleDetail() {
      const res = await apiArticleDetail(hasId);
      console.log(res.data, "ressss");
      if (res.data.cover) {
        forminstace.setFieldsValue({
          ...res.data,
          type: res.data.cover.type,
        });
        setMaxCount(res.data.cover.type);
        setImageList(
          res.data.cover.images.map((item) => {
            return { url: item };
          })
        );
      }
    }
    if (hasId?.toString().length > 0) {
      getArticleDetail();
    }
    // Clear the effect
    return () => {
      vd?.destroy();
      setVd(undefined);
    };
  }, [hasId, forminstace]);

  // 上传  和提交
  const onRadioChange = function (e) {
    if (e.target.value) {
      setShow(true);
    } else {
      setShow(false);
    }
    setMaxCount(e.target.value);
  };
  const [show, setShow] = useState(true);
  const [maxCount, setMaxCount] = useState(1);
  const [imageList, setImageList] = useState([]);

  const onFileChange = function (file) {
    console.log(file);

    setImageList(file.fileList);
  };
  const onSubmit = async function ({ channel_id, title, type }) {
    const subVal = {
      title,
      content: vd.getHTML(),
      cover: {
        type,
        images: imageList.map((item) => {
          if (item.response) {
            return item.response.data.url;
          } else {
            return item.url;
          }
        }),
      },
      channel_id,
    };
    console.log(subVal);
    await apiSubmitArticle(subVal);
    messageApi.open({
      type: "success",
      content: "发布文章成功",
    });
    forminstace.resetFields();
  };

  return (
    <>
      {contextHolder}
      <div className="publish">
        <Card
          title={
            <Breadcrumb
              items={[
                {
                  title: <Link to={"/"}>首页</Link>,
                },
                {
                  title: hasId ? "编辑文章" : "发布文章",
                },
              ]}
            />
          }
        >
          <Form
            form={forminstace}
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 16 }}
            initialValues={{ type: 1, title: "", channel_id: "" }}
            onFinish={onSubmit}
          >
            <Form.Item
              label="标题"
              name="title"
              rules={[{ required: true, message: "请输入文章标题" }]}
            >
              <Input placeholder="请输入文章标题" style={{ width: 400 }} />
            </Form.Item>
            <Form.Item
              label="频道"
              name="channel_id"
              rules={[{ required: true, message: "请选择文章频道" }]}
            >
              <Select placeholder="请选择文章频道" style={{ width: 400 }}>
                {channels.map((item) => {
                  return (
                    <Option value={item.id} key={item.id}>
                      {item.name}
                    </Option>
                  );
                })}
              </Select>
            </Form.Item>

            <Form.Item label="封面">
              <Form.Item name="type">
                <Radio.Group name="radiogroup" onChange={onRadioChange}>
                  <Radio value={1}>单图</Radio>
                  <Radio value={3}>三图</Radio>
                  <Radio value={0}>无图</Radio>
                </Radio.Group>
              </Form.Item>
              {show && (
                <Upload
                  name="image"
                  listType="picture-card"
                  className="avatar-uploader"
                  accept="image/*"
                  multiple
                  maxCount={maxCount}
                  showUploadList
                  action="http://geek.itheima.net/v1_0/upload"
                  onChange={onFileChange}
                  fileList={imageList}
                  progress={{
                    strokeColor: {
                      "0%": "#108ee9",
                      "100%": "#87d068",
                    },
                    size: 3,
                    format: (percent) =>
                      percent && `${parseFloat(percent.toFixed(2))}%`,
                  }}
                >
                  <div style={{ marginTop: 8 }}>
                    <PlusOutlined />
                  </div>
                </Upload>
              )}
            </Form.Item>

            <Form.Item label="内容">
              {/* markdown */}
              <div id="vditor" className="vditor" />
            </Form.Item>

            <Form.Item wrapperCol={{ offset: 4 }}>
              <Space>
                <Button size="large" type="primary" htmlType="submit">
                  发布文章
                </Button>
              </Space>
            </Form.Item>
          </Form>
        </Card>
      </div>
    </>
  );
};

export default Publish;
